package com.leesche.netdoll.communication.protocol.decoder;

import java.io.UnsupportedEncodingException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.leesche.framework.core.lang.ArrayUtil;
import com.leesche.framework.core.lang.StringUtil;

public class TrimZeroAsciiResolver implements Resolver<String> {

	private static final Logger logger = LogManager.getLogger(TrimZeroAsciiResolver.class);

	@Override
	public String resolve(byte[] src) {

		String value = StringUtil.EMPTY;

		int nonZeroIndex = src.length - 1;

		for (int i = nonZeroIndex; i > 0; i--) {
			if (src[i] != 0x00) {
				nonZeroIndex = i;
				break;
			}
		}

		byte[] real = ArrayUtil.subarray(src, 0, nonZeroIndex + 1);

		try {
			value = new String(real, "ascii");
		} catch (UnsupportedEncodingException e) {
			logger.catching(e);
		}

		return value;
	}

}
